package xyz.xiezc.mzix.common.dto;

import cn.hutool.core.bean.BeanUtil;
import lombok.Data;

import java.net.HttpCookie;
import java.util.*;
import java.util.stream.Collectors;

@Data
public class PageDTO {

  /**
   * 页面的id
   */
  Long id;

  String code;

  String url;
  /**
   * 响应的
   */
  String contentType;

  Request request=new Request();

  Response response;

  Map<String, Object> attribute = new HashMap<>();

  public List<PageDTO> nextPage() {
    List<String> nextUrls = (List<String>) this.getAttribute().get("nextUrls");
    List<PageDTO> nextPages = nextUrls.parallelStream().map(nextUrl -> {
      PageDTO pageDTO = BeanUtil.copyProperties(this, PageDTO.class);
      pageDTO.setId(null);
      pageDTO.setUrl(nextUrl);
      request.setUrl(nextUrl);
      request.getHeaders().put("referer", Arrays.asList(this.url));

      pageDTO.setContentType(null);
      pageDTO.setAttribute(new HashMap<>());

      Map<String, List<String>> headers = response.getHeaders();
      List<String> cookies = headers.getOrDefault("Set-Cookie", new ArrayList<>());
      cookies.addAll(headers.getOrDefault("set-cookie", new ArrayList<>()));
      pageDTO.getAttribute().put("set-cookie", cookies);
      return pageDTO;
    }).collect(Collectors.toList());
    return nextPages;
  }

}
